xquery version "1.0";
module namespace ddi-exist-utils="http://code.google.com/p/ddi-exist/";

(:ddi namespaces:)
declare namespace g = "ddi:group:3_1";
declare namespace dc="ddi:dcelements:3_1";
declare namespace d="ddi:datacollection:3_1"; 
declare namespace dc2="http://purl.org/dc/elements/1.1/"; 
declare namespace s="ddi:studyunit:3_1"; 
declare namespace c="ddi:conceptualcomponent:3_1";
declare namespace r="ddi:reusable:3_1"; 
declare namespace a="ddi:archive:3_1"; 
declare namespace ddi="ddi:instance:3_1"; 
declare namespace l="ddi:logicalproduct:3_1";

(:validate a document against its schema:)
declare function ddi-exist-utils:validate($document as xs:string, $version as xs:string) as node()*
{
    (: parse into node :) 
    let $parsed := util:parse($document)
    
    let $version := 
        if(empty($version))
        then
            if($parsed/codebook)
            then
                "2_1"
            else
                "3_1"
        else
            "3_1"
        
    
    return if(count($parsed) = 1) then
        (: validate :)
    
        if($version = "3_1") 
    	   then validation:jaxv-report($parsed , xs:anyURI('/db/ddi/xsd/3_1/instance.xsd'))
    	else if($version = "3_0") 
           then validation:jaxv-report($parsed , xs:anyURI('/db/ddi/xsd/3_0/instance.xsd'))
        else if($version = "2_1") 
           then validation:jaxv-report($parsed , xs:anyURI('/db/ddi/xsd/2_1/ddi_2_1.xsd'))
        else
           <error>the version is not supported</error>
    
    else
        <error>the document must contain one node</error>
};

declare function ddi-exist-utils:validate($document as xs:string) as node()*{
    ddi-exist-utils:validate($document, ())
};

(:get the status for the collection:)
declare function ddi-exist-utils:status($collection as node()*) as node()*{
    <status>
        <languages>
            {
                for $language in distinct-values($collection//@xml:lang)
                    return <language>{$language}</language>
            }
        </languages>
        <DDIInstances>{count($collection/ddi:DDIInstance)}</DDIInstances>
        <studies>{count($collection//s:StudyUnit)}</studies>
        <questionschemes>{count($collection//d:QuestionScheme)}</questionschemes>
        <questions>{count($collection//d:QuestionText/..)}</questions>
        <variables>{count($collection//l:Variable)}</variables>
    </status>
};

declare function ddi-exist-utils:renderQuestion($collection as node()) as node(){
    <status>
        
    </status>
};

